<template>
  <div class="app-container">
    <el-form :model="state.form" :rules="rules" label-width="120px" :disabled="!state.edit">
      <el-form-item :label="$t('systemUser.table.userName')" prop="username">
        <el-input v-model="state.form.username" />
      </el-form-item>
      <el-form-item :label="$t('systemUser.table.email')" prop="email">
        <el-input v-model="state.form.email" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" show-password v-model="state.form.password" />
      </el-form-item>
      <el-form-item :label="$t('systemUser.table.nickName')">
        <el-input v-model="state.form.nickname" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="state.form.phone" />
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="state.form.sex">
          <el-option key="1" :value="1" label="男"></el-option>
          <el-option key="2" :value="2" label="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="年龄">
        <el-input v-model="state.form.age" type="number" />
      </el-form-item>

      <el-form-item label="钉钉绑定">
        <template v-if="state.form.dingFlag">
          <svg-icon font-size="2rem" icon-class="security" />
          <el-tag type="success">已认证</el-tag>
        </template>
        <template v-else>
          <svg-icon font-size="2rem" icon-class="warring" />
          <el-button type="primary" @click="initDingJs">去绑定</el-button>
        </template>
      </el-form-item>
    </el-form>
    <el-dialog v-model="state.showDingDingQR" title="钉钉绑定" center align-center width="21.4rem">
      <div id="self_defined_element" class="self-defined-classname"></div>
    </el-dialog>
    <el-button v-if="!state.edit" type="primary" @click="state.edit = true">编辑</el-button>
    <el-button v-if="state.edit" type="primary" @click="onSubmit">{{$t('common.button.save')}}</el-button>
    <el-button @click="onCancel">{{$t('common.button.back')}}</el-button>
  </div>
</template>
<script setup lang="ts">
import {  selectOne, update, BaseUser } from './api/base-user'
import { getInfoReq, getDingDingSystem, getStateToken, dingdingAuth } from './api/user'
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormRules } from 'element-plus'

const route = useRoute()
const router = useRouter()

const { proxy }: any = getCurrentInstance()
const state = reactive({
  form: {
    sex: 1,
    status: 1,
    age: null,
    dingFlag: true
  } as BaseUser,
  dictProvince: { '0': '' },
  dictCity: { '0': '' },
  dictDistrict: { '0': '' },
  cities: <any>[],
  district: <any>[],
  dictCountry: {},
  edit: false,
  showDingDingQR: false
})

const onCancel = () => {
  router.back()
}

const validatePasswoed = (rule: any, value: any, callback: any) => {
  if (state.form.id === null || state.form.id === undefined) {
    if (value === '') {
      callback(new Error('请输入密码'))
    }
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ validator: validatePasswoed, trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: ['blur', 'change'] },
    { type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }
  ]
})
const onSubmit = async () => {
  const data = await update(state.form)
  proxy.$message({ message: proxy.$t('common.message.editSuccessfully'), type: 'success' })
  router.go(-1)
}
const initDingJs = async () => {
  const dingSystem = await getDingDingSystem()
  const token = await getStateToken(state.form.id)
  console.log(token.data);
  new Promise((res, rej) => {
    res((state.showDingDingQR = true))
  }).then(() => {
    // 获取钉钉的信息
    window.DTFrameLogin(
      {
        id: 'self_defined_element'
      },
      {
        redirect_uri: dingSystem.data.redirect_uri,
        client_id: dingSystem.data.client_id,
        scope: 'openid',
        response_type: 'code',
        state: token.data,
        prompt: 'consent'
      },
      (loginResult) => {
        const { redirectUrl, authCode, state } = loginResult
        authDingDing(authCode,state)
      },
      (errorMsg) => {
        alert(errorMsg)
        // 这里一般需要展示登录失败的具体原因
        ElMessage({
          type: 'error',
          message: errorMsg
        })
      }
    )
  })
}
const authDingDing = async (code,token) => {
  state.showDingDingQR = false
  dingdingAuth(code,token).then((res)=>{
    state.form.dingFlag = true
  })

  

}
onMounted(() => {
  getProfile()
})

const getProfile = async () => {
  const res = await getInfoReq()
  state.form = res.data
}
</script>

<style lang="scss" scoped>
.el-input {
  width: 300px;
}

.el-select {
  width: 300px;
}

.el-textarea {
  width: 300px;
}
// .self-defined-classname {
//   width: 300px;
//   height: 300px;
// }
</style>
